﻿<!DOCTYPE html>
	<head>
		<meta charset="utf-8" />
		<title>多级菜单</title>
		<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
		<script type="text/javascript" src="js/jquery-2.0.3.min.js"></script>
		<script type="text/javascript" src="js/bootstrap.min.js"></script>
	</head>
	<style type="text/css">
		
	</style>
	<body>
		<!-- 存放菜单 -->
		<div>
			<ul id="one"></ul>
		</div>
		<hr>
		<!-- 存放级数 -->
		<div>
			<span>菜单层级:</span><span id="how"></span>
		</div>
	</body>
	<script type="text/javascript">
		//模拟的数据(js多级菜单---菜单级数未知---数据自行添加id不能重复)
		let tree=[  {id:"1",pid:"",name:"一级菜单"},
					{id:"2-1",pid:"1",name:"二级菜单"},
					{id:"2-2",pid:"1",name:"二级菜单"},
					{id:"2-3",pid:"1",name:"二级菜单"},
					{id:"3-2",pid:"2-2",name:"2-2下面的三级菜单"},
					{id:"3-1",pid:"2-1",name:"2-1下面的三级菜单"},
					{id:"3-3",pid:"2-1",name:"2-1下面的三级菜单"},
					{id:"4-1",pid:"3-1",name:"3-1下面的四级菜单"},
					{id:"4-2",pid:"3-2",name:"3-2下面的四级菜单"},
					{id:"5-1",pid:"4-2",name:"4-2下面的五级菜单"},
					{id:"5-2",pid:"4-2",name:"4-2下面的五级菜单"}
		];
		//分组(按等级分组)
		getDate();
		function getDate(){
			//存放所有数据的数组
			var all=[];
			for(var i=0;i<tree.length;i++){
				var small=[];
				for(var j=0;j<tree.length;j++){
					if(tree[i].id[0]==tree[j].id[0]){
						small.push(tree[j].id,tree[j].name,tree[j].pid);
					}
				}
				all.push(small);
			}
			deleteRepeat(all);
		}
		//二维数组去重(防止有两组一样)
		function deleteRepeat(arr){
			var result = arr.reduce((function () {
			    var map = {};
			    return function (result, next) {
				    var key = next[0];
				    if (!map[key]) {
				      map[key] = true;
				      result.push(next);
				    }
				    return result;
			    };
			})(), []);
			var all_arr=eval(JSON.stringify(result));
			$("#how").text(all_arr.length);
			dealWith(all_arr);
		}
		//开始放数据
		function dealWith(all){
			for(var i=0;i<all.length;i++){
				for(var j=1;j<all[i].length;){
					var html="<li class="+all[i][j-1]+">"+all[i][j]+"</li>";
					var ul_id=all[i][1+j];
					j=j+3;
					over(html,ul_id)
				}
			}
		}
		//最终数据
		function over(html,ul_id){
			if(ul_id==""){
				$("#one").append(html);
			}else{
				$("."+ul_id).append("<ul>"+html+"</ul>");
				overOot(ul_id);
			}
		}
		//点击隐藏
		function overOot(cla){
			$("."+cla+" ul").hide();
			$("."+cla).click(function(){
				console.log("1");
				$("."+cla+" ul").show();
				$("."+cla+" ul ul").hide();
				event.stopPropagation();
				return false;
			})
		}
		$(document).bind('click', function (e) {
            var e = e || window.event; //浏览器兼容性
            var elem = e.target || e.srcElement;
            while (elem) { //循环判断至跟节点，防止点击的是div子元素
                if (elem.id && (elem.id == 'one')) {
                    return;
                }
                elem = elem.parentNode;
            }
            $('#one li ul').css('display', 'none'); //点击的不是div或其子元素
        });
	</script>
</html>